<script setup>
import {
  reactive,
  ref,
  watch,
  defineProps,
  defineEmits
} from "vue";
import {
  CloudUploadOutlined,
} from "@ant-design/icons-vue";
import { Form, message } from "ant-design-vue";
import defaultSetting from "@/common/utils/defaultSetting";
import request, { errorHandler } from "@/common/utils/request";
import store from "@/store";

const useForm = Form.useForm;
const uploadResponse = (response) => {
  const { code } = response;
  if (code === 1000) {
    return Promise.resolve(response.data);
  } else {
    return errorHandler({ data: response });
  }
};

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object,
    default: () => {},
  },
});

const tabs = [
  { tab: "输入问答", key: "inputQA" },
  { tab: "批量上传", key: "batchUpload" },
];
const emit = defineEmits(["update:visible", "cancel"]);

let baseUrl = defaultSetting.requestDomain;
if (process.env.NODE_ENV === "development") {
  baseUrl = baseUrl + "/api";
}

const activeKey = ref("inputQA");

const state = reactive({
  importCsvLoading: false,
  importCsvData: [],
  modalConfirmLoading: false,
});

const inputFormRef = reactive({
  question: "",
  answer: "",
});

const inputRulesRef = reactive({
  question: [{ required: true, message: "请输入问题" }],
  answer: [{ required: true, message: "请输入答案" }],
});

const { resetFields, validate, validateInfos } = useForm(
  inputFormRef,
  inputRulesRef
);

const handleDrop = (e) => {};

// 下载模版
const downloadFile = () => {
  const filename = "templates.xlsx";
  const fileUrl = `${baseUrl}/public_web/static/file/org/template.xlsx`;
  const link = document.createElement("a");
  link.style.display = "none";
  link.href = fileUrl;
  link.setAttribute("download", filename);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 导入excel
const importCsvUploadChange = ({ file }) => {
  if (file.status === "uploading") {
    state.importCsvLoading = true;
    return;
  }

  if (file.status === "done") {
    state.importCsvLoading = false;

    uploadResponse(file.response).then(({ data }) => {
      state.importCsvData = data;
      emit("cancel", true);
    });
  }

  if (file.status === "error") {
    state.importCsvLoading = false;
    state.uploadCsvFile = null;

    message.error("上传失败");
  }
};

const handleCancel = () => {
  emit("cancel");
};

const handleSubmit = () => {
  state.modalConfirmLoading = true;
  if (activeKey.value === "inputQA") {
    validate().then(() => {
      const params = {
        title: inputFormRef.question,
        content_html: inputFormRef.answer,
        wiki_id: props.data?.wiki_id,
        team_id: store.state.user.teamId
      };

      if (props.data?.id) {
        params["id"] = props.data.id;
      }

      request
        .post("/work_ai", "/user/knowledge/document/qa/text", params)
        .then(() => {
          state.modalConfirmLoading = false;
          emit("cancel", true);
        })
        .catch((err) => {
          state.modalConfirmLoading = false;
        });
    });
  } else {
    emit("cancel", true);
  }
};

watch(
  () => props.visible,
  (val) => {
    if (val) {
      if (props?.data?.id) {
        inputFormRef.question = props.data?.title;
        inputFormRef.answer = props.data?.content_html;
      } else {
        resetFields();
      }
    }
  }
);
</script>

<template>
  <a-modal
    @cancel="handleCancel"
    @ok="handleSubmit"
    :confirmLoading="state.modalConfirmLoading"
    :width="520"
    :visible="visible"
    :bodyStyle="{
      paddingTop: 0,
    }"
    title="录入问答"
  >
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane tab="输入问答" key="inputQA">
        <a-form :model="inputFormRef" layout="vertical">
          <a-form-item label="" v-bind="validateInfos.question">
            <a-input
              v-model:value="inputFormRef.question"
              :maxlength="300"
              placeholder="输入问题，请输入 300 以内的字符"
            />
          </a-form-item>
          <a-form-item label="" v-bind="validateInfos.answer">
            <a-textarea
              :rows="10"
              v-model:value="inputFormRef.answer"
              :maxlength="3000"
              placeholder="输入答案，请输入 3000 以内的字符"
            />
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane tab="批量上传" key="batchUpload">
        <div class="content">
          <div style="color: #9da3af; font-size: 12px; margin-bottom: 10px">
            <span
              style="color: var(--ss-primary-color); cursor: pointer"
              @click="downloadFile"
              >点击此处下载模板</span
            >
            完成填写后再上传，问题总数不超过条10000条
          </div>
          <div style="height: 180px">
            <a-upload-dragger
              name="file"
              accept=".xls,.xlsx"
              :multiple="false"
              :action="`${baseUrl}/work_ai/user/knowledge/document/qa/upload`"
              @change="importCsvUploadChange"
              @drop="handleDrop"
              :data="{
                user_token: $utils.getToken(),
                wiki_id: data?.wiki_id,
                org_id: $utils.getOrgId(),
                team_id: $utils.getCurrentTeam(),
              }"
            >
              <p style="font-size: 60px; color: #606266">
                <CloudUploadOutlined />
              </p>
              <p class="ant-upload-text" style="color: #606266">
                将文件拖到此处，或<span style="color: var(--ss-primary-color)"
                  >点击上传</span
                >
              </p>
            </a-upload-dragger>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>

    <template v-if="activeKey === 'batchUpload'" #footer></template>
  </a-modal>
</template>

<style lang="less" scoped></style>
